package thread;
/** 有效缩小同步范围可以保证并发安全的前提下提高并发效率
 *
 * 同步块
 * synchronized(同步监视器对象)
 * 需要多个线程同步执行的代码片段
 * */
public   class SyncDemo2 {
    public static void main(String[] args) {
      //  Shop shop = new Shop();
        Shop shop1 = new Shop();
        Shop shop2 = new Shop();
        Thread t1 = new Thread("王克晶") {
            public void run() {
                //shop.buy();
                shop1.buy();
            }
        };
        Thread t2 = new Thread("范传奇") {
            public void run() {
                //shop.buy();
                shop2.buy();
            }
        };
        t1.start();
        t2.start();
    }
}
   class Shop{
    public  void buy(){
       // public synchronized void buy(){  这个跟下方的方法冲突
            try {
                Thread t = Thread.currentThread();
                System.out.println(t.getName()+":正在挑衣服");
                Thread.sleep(5000);
                synchronized (this){//要求：所有需要同步块的  new Object()  t  字面量"hello" 和123
                System.out.println(t.getName()+":正在试衣服");
                Thread.sleep(5000);}
                System.out.println(t.getName()+":结帐离开");
            } catch (InterruptedException e) {
            }
        }
}


